import json
import logging
import re

from .oAuth_utils import login_qq, base_login

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.views import View
from .models import User
from django.core.mail import send_mail as send
from django.conf import settings
from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse, HttpResponse

LOG = logging.getLogger(__name__)


class Login(View):
    login_kwargs = {
        'login': 'login_func',
        'login_qq': 'login_qq',
        'logout': 'logout_func',
        'register': 'register_func',
        'verify_code': 'set_verify_code',
    }

    user_email_info = {}

    def get(self, req, **kwargs):
        return getattr(Login, self.login_kwargs[kwargs['slug']], 'common_func')(req)

    def post(self, req, **kwargs):
        return getattr(Login, self.login_kwargs[kwargs['slug']], 'common_func')(req)

    @classmethod
    def get_data(cls, req):
        return json.loads(req.body.decode('utf8'))

    @classmethod
    def common_func(cls, req):
        return render(req, 'login.html')

    @classmethod
    def login_qq(self, req):
        return redirect(
            'https://graph.qq.com/oauth2.0/authorize?response_type=token&client_id=101580560&redirect_uri=http://www.bianbingdang.com/auth/login&qq=true')

    @classmethod
    def login_func(cls, req):
        # 如果QQ互联登陆，跳转到QQ登陆
        qq_flag = req.GET.get('qq')
        if qq_flag in ['true', True, 'True']:
            return login_qq(req)
        else:
            return base_login(req)

    @classmethod
    def logout_func(cls, req):
        if not req.user.is_authenticated:
            raise Exception
        else:
            logout(req)
            return redirect('/')

    @classmethod
    def register_func(cls, req):
        register_info = cls.get_data(req)
        kwargs = {}
        kwargs['code'] = 500
        username = register_info['username']
        email = register_info['email']
        password = register_info['password']

        LOG.info('register info, username:%s,emails:%s' % (username, email))

        if not username or not email or not password:
            kwargs['message'] = '用户名、邮件、验证码或密码不能为空'
            kwargs['error'] = 'empty'
            return JsonResponse(kwargs)

        reg_user = User.objects.filter(username=username)
        if reg_user:
            kwargs['message'] = '用户名已被注册'
            return JsonResponse(kwargs)
        reg_email = User.objects.filter(email=email)
        if reg_email:
            kwargs['message'] = '邮箱已被使用,请更换'
            return JsonResponse(kwargs)

        User.objects.create(username=username, password=make_password(password), email=email, article_number=0, money=0)
        user = authenticate(username=username, password=password)
        login(req, user)
        kwargs['code'] = 200
        return JsonResponse(kwargs)

    @classmethod
    def send_mail(cls, code, to):
        if not isinstance(code, str):
            code = str(code)
        msg = '<h1>欢迎注册' + settings.BLOG_NAME + '博客</h1>' \
                                                '<p style="font-size:large"> : ' + str(code) + '</p>'
        LOG.warning('to email 【%s】 【%s】 【%s】' % (code, to, msg))
        send(settings.BLOG_NAME, '变饼档', settings.EMAIL_FROM,
             (to,),
             html_message=msg)

    @classmethod
    def set_verify_code(cls, req):
        email = req.GET['email']
        verify_code = req.GET['verify_code']
        regex_email = re.match('[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}', email)
        if not regex_email:
            return JsonResponse([{'code': 500}], safe=False)

        LOG.info('create verify success %s' % verify_code)

        cls.send_mail(verify_code, email)
        return JsonResponse([{'code': 200}], safe=False)
